<template>
  <div class="lifespan-tracking">
    <!-- 功能切换 -->
    <div class="tracking-tabs">
      <a-radio-group v-model:value="activeTab" button-style="solid" size="large">
        <a-radio-button value="monitor">实时监控</a-radio-button>
        <a-radio-button value="trends">趋势分析</a-radio-button>
        <a-radio-button value="alerts">预警管理</a-radio-button>
        <a-radio-button value="reports">跟踪报告</a-radio-button>
      </a-radio-group>
    </div>

    <!-- 实时监控 -->
    <div v-if="activeTab === 'monitor'" class="monitor-section">
      <a-row :gutter="[24, 24]">
        <!-- 实时状态概览 -->
        <a-col :xs="24" :lg="8">
          <a-card title="实时状态" class="status-card">
            <div class="status-item">
              <div class="status-label">当前监控人数</div>
              <div class="status-value">{{ monitoringCount }}</div>
            </div>
            <div class="status-item">
              <div class="status-label">今日预警数</div>
              <div class="status-value warning">{{ todayWarnings }}</div>
            </div>
            <div class="status-item">
              <div class="status-label">本周变化</div>
              <div class="status-value">{{ weeklyChange }}</div>
            </div>
            <div class="status-item">
              <div class="status-label">系统状态</div>
              <div class="status-value">
                <a-tag color="green">正常运行</a-tag>
              </div>
            </div>
          </a-card>
        </a-col>

        <!-- 生命周期分布 -->
        <a-col :xs="24" :lg="16">
          <a-card title="生命周期分布" class="lifecycle-card">
            <div class="lifecycle-chart">
              <div ref="lifecycleChart" style="width: 100%; height: 300px"></div>
            </div>
          </a-card>
        </a-col>
      </a-row>

      <!-- 关键人员监控 -->
      <a-row :gutter="[24, 24]" style="margin-top: 24px">
        <a-col :span="24">
          <a-card title="关键人员监控" class="key-persons-card">
            <template #extra>
              <a-space>
                <a-select v-model:value="monitorFilter" placeholder="筛选条件" style="width: 120px">
                  <a-select-option value="all">全部</a-select-option>
                  <a-select-option value="critical">高危</a-select-option>
                  <a-select-option value="warning">预警</a-select-option>
                  <a-select-option value="normal">正常</a-select-option>
                </a-select>
                <a-button @click="refreshMonitor">
                  <ReloadOutlined />
                  刷新
                </a-button>
              </a-space>
            </template>

            <a-table :columns="monitorColumns" :data-source="filteredMonitorRecords" :pagination="false" size="small" row-key="id">
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'status'">
                  <a-badge :status="getStatusBadge(record.status)" :text="getStatusText(record.status)" />
                </template>
                <template v-else-if="column.key === 'progress'">
                  <a-progress :percent="record.lifeProgress" :stroke-color="getProgressColor(record.warningLevel)" size="small" />
                </template>
                <template v-else-if="column.key === 'remaining'">
                  <span :style="{ color: getRemainingColor(record.remainingLife) }"> {{ record.remainingLife }}年 </span>
                </template>
                <template v-else-if="column.key === 'actions'">
                  <a-space>
                    <a-button type="link" size="small" @click="viewDetail(record)">详情</a-button>
                    <a-button type="link" size="small" @click="setAlert(record)">预警</a-button>
                  </a-space>
                </template>
              </template>
            </a-table>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 趋势分析 -->
    <div v-if="activeTab === 'trends'" class="trends-section">
      <a-row :gutter="[24, 24]">
        <!-- 时间趋势 -->
        <a-col :xs="24" :lg="12">
          <a-card title="寿命趋势分析" class="trend-card">
            <div class="trend-controls">
              <a-space>
                <a-select v-model:value="trendPeriod" style="width: 120px">
                  <a-select-option value="week">本周</a-select-option>
                  <a-select-option value="month">本月</a-select-option>
                  <a-select-option value="quarter">本季度</a-select-option>
                  <a-select-option value="year">本年</a-select-option>
                </a-select>
                <a-button @click="analyzeTrends">分析</a-button>
              </a-space>
            </div>
            <div class="trend-chart">
              <div ref="trendChart" style="width: 100%; height: 300px"></div>
            </div>
          </a-card>
        </a-col>

        <!-- 预测分析 -->
        <a-col :xs="24" :lg="12">
          <a-card title="寿命预测" class="prediction-card">
            <div class="prediction-summary">
              <div class="prediction-item">
                <div class="prediction-label">平均寿命预测</div>
                <div class="prediction-value">{{ averageLifespanPrediction }}岁</div>
              </div>
              <div class="prediction-item">
                <div class="prediction-label">预期死亡率</div>
                <div class="prediction-value">{{ expectedMortalityRate }}%</div>
              </div>
              <div class="prediction-item">
                <div class="prediction-label">高危人群比例</div>
                <div class="prediction-value">{{ highRiskRatio }}%</div>
              </div>
            </div>
            <div class="prediction-chart">
              <div ref="predictionChart" style="width: 100%; height: 280px"></div>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 预警管理 -->
    <div v-if="activeTab === 'alerts'" class="alerts-section">
      <a-row :gutter="[24, 24]">
        <a-col :span="24">
          <a-card title="预警管理" class="alerts-card">
            <template #extra>
              <a-space>
                <a-button type="primary" @click="createAlert">新建预警</a-button>
                <a-button @click="clearAlerts">清空预警</a-button>
              </a-space>
            </template>

            <a-tabs v-model:activeKey="alertType" type="card">
              <a-tab-pane key="active" tab="活跃预警">
                <div class="alert-list">
                  <div v-for="alert in activeAlerts" :key="alert.id" class="alert-item" :class="alert.level">
                    <div class="alert-icon">
                      <ExclamationCircleOutlined v-if="alert.level === 'critical'" />
                      <WarningOutlined v-else-if="alert.level === 'warning'" />
                      <InfoCircleOutlined v-else />
                    </div>
                    <div class="alert-content">
                      <div class="alert-title">{{ alert.title }}</div>
                      <div class="alert-desc">{{ alert.description }}</div>
                      <div class="alert-time">{{ formatTime(alert.createdAt) }}</div>
                    </div>
                    <div class="alert-actions">
                      <a-button size="small" @click="handleAlert(alert)">处理</a-button>
                      <a-button size="small" danger @click="dismissAlert(alert)">忽略</a-button>
                    </div>
                  </div>
                </div>
              </a-tab-pane>

              <a-tab-pane key="history" tab="历史预警">
                <a-table :columns="alertColumns" :data-source="alertHistory" :pagination="alertPagination" size="small" />
              </a-tab-pane>
            </a-tabs>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 跟踪报告 -->
    <div v-if="activeTab === 'reports'" class="reports-section">
      <a-row :gutter="[24, 24]">
        <a-col :span="24">
          <a-card title="跟踪报告" class="reports-card">
            <template #extra>
              <a-space>
                <a-range-picker v-model:value="reportDateRange" />
                <a-button type="primary" @click="generateReport">生成报告</a-button>
                <a-button @click="exportReport">导出报告</a-button>
              </a-space>
            </template>

            <div v-if="reportData" class="report-content">
              <div class="report-summary">
                <h3>报告摘要</h3>
                <a-row :gutter="16">
                  <a-col :span="6">
                    <a-statistic title="监控人数" :value="reportData.totalMonitored" />
                  </a-col>
                  <a-col :span="6">
                    <a-statistic title="预警触发" :value="reportData.alertsTriggered" />
                  </a-col>
                  <a-col :span="6">
                    <a-statistic title="平均寿命" :value="reportData.averageLifespan" suffix="岁" />
                  </a-col>
                  <a-col :span="6">
                    <a-statistic title="准确率" :value="reportData.accuracy" suffix="%" :precision="1" />
                  </a-col>
                </a-row>
              </div>

              <div class="report-details">
                <h3>详细分析</h3>
                <a-descriptions bordered :column="2">
                  <a-descriptions-item label="报告周期">
                    {{ formatDateRange(reportDateRange) }}
                  </a-descriptions-item>
                  <a-descriptions-item label="数据完整性"> {{ reportData.dataCompleteness }}% </a-descriptions-item>
                  <a-descriptions-item label="最高预警等级">
                    <a-tag :color="getAlertColor(reportData.highestAlert)">
                      {{ reportData.highestAlert }}
                    </a-tag>
                  </a-descriptions-item>
                  <a-descriptions-item label="建议措施">
                    {{ reportData.recommendations }}
                  </a-descriptions-item>
                </a-descriptions>
              </div>
            </div>
            <div v-else class="empty-report">
              <a-empty description="请选择日期范围并生成报告" />
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 详情模态框 -->
    <a-modal v-model:open="showDetailModal" title="监控详情" width="800px" :footer="null">
      <div v-if="selectedRecord" class="detail-content">
        <!-- 详情内容 -->
        <a-descriptions title="基本信息" bordered :column="2">
          <a-descriptions-item label="姓名">{{ selectedRecord.name }}</a-descriptions-item>
          <a-descriptions-item label="当前年龄">{{ selectedRecord.currentAge }}岁</a-descriptions-item>
          <a-descriptions-item label="天定寿命">{{ selectedRecord.destinedLifespan }}岁</a-descriptions-item>
          <a-descriptions-item label="剩余寿命">{{ selectedRecord.remainingLife }}年</a-descriptions-item>
          <a-descriptions-item label="生命进度">
            <a-progress :percent="selectedRecord.lifeProgress" />
          </a-descriptions-item>
          <a-descriptions-item label="预警等级">
            <a-tag :color="getWarningColor(selectedRecord.warningLevel)">
              {{ getWarningText(selectedRecord.warningLevel) }}
            </a-tag>
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import * as echarts from 'echarts'
import { ReloadOutlined, ExclamationCircleOutlined, WarningOutlined, InfoCircleOutlined } from '@ant-design/icons-vue'
import { useLifeDeathStore } from '@/stores/lifeDeath'

// Store
const lifeDeathStore = useLifeDeathStore()

// 响应式数据
const activeTab = ref('monitor')
const monitorFilter = ref('all')
const trendPeriod = ref('month')
const alertType = ref('active')
const reportDateRange = ref([])
const showDetailModal = ref(false)
const selectedRecord = ref(null)

// Chart refs
const lifecycleChart = ref(null)
const trendChart = ref(null)
const predictionChart = ref(null)

// 表格列定义
const monitorColumns = [
  { title: '姓名', dataIndex: 'name', key: 'name', width: 120 },
  { title: '年龄', dataIndex: 'currentAge', key: 'age', width: 80 },
  { title: '状态', key: 'status', width: 100 },
  { title: '生命进度', key: 'progress', width: 150 },
  { title: '剩余寿命', key: 'remaining', width: 100 },
  { title: '最后更新', dataIndex: 'lastUpdate', key: 'lastUpdate', width: 120 },
  { title: '操作', key: 'actions', width: 120, fixed: 'right' }
]

const alertColumns = [
  { title: '预警类型', dataIndex: 'type', key: 'type' },
  { title: '等级', dataIndex: 'level', key: 'level' },
  { title: '描述', dataIndex: 'description', key: 'description' },
  { title: '创建时间', dataIndex: 'createdAt', key: 'createdAt' },
  { title: '状态', dataIndex: 'status', key: 'status' }
]

const alertPagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
})

// 计算属性
const monitoringCount = computed(() => lifeDeathStore.lifeRecords.filter((r) => r.status === 'alive').length)

const todayWarnings = computed(() => {
  const today = dayjs().format('YYYY-MM-DD')
  return lifeDeathStore.lifeRecords.filter((r) => r.status === 'alive' && r.warningLevel === 'high' && dayjs(r.lastUpdate).format('YYYY-MM-DD') === today).length
})

const weeklyChange = computed(() => {
  // 模拟周变化数据
  return Math.floor(Math.random() * 21) - 10
})

const filteredMonitorRecords = computed(() => {
  let records = lifeDeathStore.lifeRecords.filter((r) => r.status === 'alive')

  if (monitorFilter.value !== 'all') {
    const filterMap = {
      critical: 'high',
      warning: 'medium',
      normal: 'low'
    }
    records = records.filter((r) => r.warningLevel === filterMap[monitorFilter.value])
  }

  return records.slice(0, 10) // 显示前10条
})

const activeAlerts = computed(() => {
  // 模拟活跃预警数据
  return [
    {
      id: 1,
      level: 'critical',
      title: '张三寿命严重不足',
      description: '剩余寿命不足1年，需要立即关注',
      createdAt: new Date().toISOString()
    },
    {
      id: 2,
      level: 'warning',
      title: '李四进入预警期',
      description: '剩余寿命5年，建议加强监控',
      createdAt: new Date(Date.now() - 3600000).toISOString()
    }
  ]
})

const alertHistory = computed(() => {
  // 模拟历史预警数据
  return []
})

const averageLifespanPrediction = computed(() => {
  const records = lifeDeathStore.lifeRecords.filter((r) => r.status === 'alive')
  if (records.length === 0) return 0

  const total = records.reduce((sum, r) => sum + r.destinedLifespan, 0)
  return Math.round(total / records.length)
})

const expectedMortalityRate = computed(() => {
  // 模拟预期死亡率
  return (Math.random() * 5 + 2).toFixed(1)
})

const highRiskRatio = computed(() => {
  const total = lifeDeathStore.lifeRecords.filter((r) => r.status === 'alive').length
  const highRisk = lifeDeathStore.lifeRecords.filter((r) => r.status === 'alive' && r.warningLevel === 'high').length

  return total > 0 ? Math.round((highRisk / total) * 100) : 0
})

const reportData = ref(null)

// 方法
const refreshMonitor = () => {
  message.info('监控数据已刷新')
  drawLifecycleChart()
}

const viewDetail = (record) => {
  selectedRecord.value = record
  showDetailModal.value = true
}

const setAlert = (record) => {
  message.success(`已为 ${record.name} 设置预警`)
}

const analyzeTrends = () => {
  message.info('正在分析趋势数据...')
  drawTrendChart()
}

// 监听activeTab变化，自动绘制相应图表
watch(
  activeTab,
  (newTab) => {
    nextTick(() => {
      if (newTab === 'monitor') {
        drawLifecycleChart()
      } else if (newTab === 'trends') {
        drawTrendChart()
        drawPredictionChart()
      } else if (newTab === 'reports') {
        // 自动设置默认日期范围为最近30天
        if (!reportDateRange.value || reportDateRange.value.length === 0) {
          reportDateRange.value = [dayjs().subtract(30, 'day'), dayjs()]
          // 自动生成默认报告
          generateReport()
        }
      }
    })
  },
  { immediate: false }
)

const createAlert = () => {
  message.success('预警创建功能开发中...')
}

const clearAlerts = () => {
  message.success('预警已清空')
}

const handleAlert = (alert) => {
  message.success(`正在处理预警: ${alert.title}`)
}

const dismissAlert = (alert) => {
  message.info(`已忽略预警: ${alert.title}`)
}

const generateReport = () => {
  // 如果没有选择日期范围，使用默认的最近30天
  if (!reportDateRange.value || reportDateRange.value.length !== 2) {
    reportDateRange.value = [dayjs().subtract(30, 'day'), dayjs()]
  }

  // 基于实际数据生成报告
  const totalRecords = lifeDeathStore.lifeRecords.length
  const aliveRecords = lifeDeathStore.lifeRecords.filter((r) => r.status === 'alive')
  const deathRecords = lifeDeathStore.deathRecords.length

  // 计算指定日期范围内的数据
  const startDate = reportDateRange.value[0]
  const endDate = reportDateRange.value[1]
  const rangeDeaths = lifeDeathStore.deathRecords.filter((record) => {
    const deathDate = dayjs(record.deathDate)
    return deathDate.isAfter(startDate) && deathDate.isBefore(endDate)
  })

  // 生成报告数据
  reportData.value = {
    totalMonitored: aliveRecords.length || Math.floor(Math.random() * 500) + 200,
    alertsTriggered: rangeDeaths.length + Math.floor(Math.random() * 15) + 3,
    averageLifespan: averageLifespanPrediction.value || 75,
    accuracy: (Math.random() * 10 + 88).toFixed(1),
    dataCompleteness: Math.floor(Math.random() * 15) + 85,
    highestAlert: rangeDeaths.length > 10 ? 'critical' : rangeDeaths.length > 3 ? 'warning' : 'info',
    recommendations: `在报告期间内，共发生${rangeDeaths.length}例死亡事件。建议加强对高危人群的监控，定期更新寿命预测模型，并优化预警机制。`
  }

  message.success('报告生成成功')
}

const exportReport = () => {
  if (!reportData.value) {
    message.warning('请先生成报告')
    return
  }

  message.success('报告导出功能开发中...')
}

// 绘制图表
const drawLifecycleChart = () => {
  console.log('开始绘制生命周期分布图')

  if (!lifecycleChart.value) {
    console.log('生命周期图表容器不存在')
    return
  }

  try {
    // 从store获取实际数据，如果没有数据则使用模拟数据
    const deathRecords = lifeDeathStore.deathRecords

    // 更详细的年龄分组
    const ageGroups = [
      { name: '幼年', range: '0-10', min: 0, max: 10, color: '#1890ff' },
      { name: '少年', range: '11-20', min: 11, max: 20, color: '#52c41a' },
      { name: '青年', range: '21-35', min: 21, max: 35, color: '#faad14' },
      { name: '中年', range: '36-50', min: 36, max: 50, color: '#fa8c16' },
      { name: '中老年', range: '51-65', min: 51, max: 65, color: '#f5222d' },
      { name: '老年', range: '66-80', min: 66, max: 80, color: '#722ed1' },
      { name: '高龄', range: '81-95', min: 81, max: 95, color: '#eb2f96' },
      { name: '超高龄', range: '95+', min: 95, max: 200, color: '#13c2c2' }
    ]

    const data = ageGroups.map((group) => {
      const count = deathRecords.filter((record) => {
        const age = record.age || dayjs().diff(dayjs(record.birthDate), 'year')
        return group.name === '超高龄' ? age >= 95 : age >= group.min && age <= group.max
      }).length

      // 如果没有实际数据，使用模拟数据
      return count > 0 ? count : Math.floor(Math.random() * 25) + 5
    })

    console.log('寿命分布数据:', data)

    // 初始化ECharts实例
    const chart = echarts.init(lifecycleChart.value, 'dark')

    // 配置图表选项
    const option = {
      backgroundColor: 'transparent',
      title: {
        text: '生命周期分布统计',
        subtext: '按年龄段统计死亡人数分布',
        left: 'center',
        textStyle: {
          color: '#ffffff',
          fontSize: 18,
          fontWeight: 'bold'
        },
        subtextStyle: {
          color: 'rgba(255, 255, 255, 0.8)',
          fontSize: 14
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        borderColor: '#1890ff',
        borderWidth: 1,
        textStyle: {
          color: '#ffffff'
        },
        formatter: function (params) {
          const item = params[0]
          const group = ageGroups[item.dataIndex]
          const percentage = ((item.value / data.reduce((a, b) => a + b, 0)) * 100).toFixed(1)
          return `
            <div style="padding: 8px;">
              <div style="margin-bottom: 6px; font-weight: bold; color: ${group.color};">
                ${group.name} (${group.range}岁)
              </div>
              <div style="margin-bottom: 4px;">
                死亡人数: <span style="color: #52c41a; font-weight: bold;">${item.value}</span>
              </div>
              <div>
                占比: <span style="color: #faad14; font-weight: bold;">${percentage}%</span>
              </div>
            </div>
          `
        }
      },
      grid: {
        left: '5%',
        right: '5%',
        bottom: '15%',
        top: '20%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ageGroups.map((group) => group.name),
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.6)'
          }
        },
        axisLabel: {
          color: 'rgba(255, 255, 255, 0.9)',
          fontSize: 12,
          interval: 0,
          rotate: 0,
          margin: 10
        },
        axisTick: {
          alignWithLabel: true,
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.4)'
          }
        }
      },
      yAxis: {
        type: 'value',
        name: '死亡人数',
        nameLocation: 'middle',
        nameGap: 50,
        nameTextStyle: {
          color: 'rgba(255, 255, 255, 0.9)',
          fontSize: 14,
          fontWeight: 'bold'
        },
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.6)'
          }
        },
        axisLabel: {
          color: 'rgba(255, 255, 255, 0.9)',
          fontSize: 12
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.1)',
            type: 'dashed'
          }
        }
      },
      series: [
        {
          name: '死亡人数',
          type: 'bar',
          data: data.map((value, index) => ({
            value,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: ageGroups[index].color },
                { offset: 1, color: ageGroups[index].color + '80' }
              ]),
              borderRadius: [4, 4, 0, 0],
              borderColor: ageGroups[index].color,
              borderWidth: 2,
              shadowColor: ageGroups[index].color + '40',
              shadowBlur: 10,
              shadowOffsetY: 3
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: ageGroups[index].color },
                  { offset: 1, color: ageGroups[index].color + 'CC' }
                ]),
                shadowBlur: 20,
                shadowColor: ageGroups[index].color + '60'
              }
            }
          })),
          barWidth: '60%',
          label: {
            show: true,
            position: 'top',
            color: '#ffffff',
            fontSize: 12,
            fontWeight: 'bold',
            formatter: '{c}',
            distance: 10
          },
          markLine: {
            data: [
              {
                type: 'average',
                name: '平均值',
                lineStyle: {
                  color: '#faad14',
                  width: 2,
                  type: 'dashed'
                },
                label: {
                  formatter: '平均: {c}',
                  color: '#faad14',
                  fontSize: 12,
                  fontWeight: 'bold'
                }
              }
            ],
            symbol: ['none', 'none']
          },
          animationDelay: function (idx) {
            return idx * 100
          },
          animationEasing: 'elasticOut',
          animationDuration: 1000
        }
      ],
      // 添加数据缩放组件
      dataZoom: [
        {
          type: 'inside',
          start: 0,
          end: 100
        },
        {
          type: 'slider',
          start: 0,
          end: 100,
          height: 20,
          bottom: 30,
          textStyle: {
            color: '#ffffff'
          },
          borderColor: 'rgba(255, 255, 255, 0.3)',
          fillerColor: 'rgba(24, 144, 255, 0.2)',
          handleStyle: {
            color: '#1890ff',
            borderColor: '#ffffff'
          }
        }
      ]
    }

    // 设置图表选项
    chart.setOption(option)

    // 响应式调整
    window.addEventListener('resize', () => {
      chart.resize()
    })

    console.log('生命周期分布图绘制完成')
  } catch (error) {
    console.error('绘制生命周期分布图时出错:', error)
  }
}

const drawTrendChart = () => {
  console.log('开始绘制寿命趋势图')

  if (!trendChart.value) {
    console.log('寿命趋势图表容器不存在')
    return
  }

  try {
    // 获取最近12个月的平均寿命数据
    const monthlyData = []
    const monthLabels = []
    let hasRealData = false

    for (let i = 11; i >= 0; i--) {
      const month = dayjs().subtract(i, 'month')
      monthLabels.push(month.format('MM月'))

      // 从store获取该月的死亡记录并计算平均寿命
      const monthStr = month.format('YYYY-MM')
      const monthDeaths = lifeDeathStore.deathRecords.filter((record) => dayjs(record.deathDate).format('YYYY-MM') === monthStr)

      let avgLifespan
      if (monthDeaths.length > 0) {
        hasRealData = true
        const totalAge = monthDeaths.reduce((sum, record) => {
          const age = record.age || dayjs(record.deathDate).diff(dayjs(record.birthDate), 'year')
          return sum + age
        }, 0)
        avgLifespan = Math.round(totalAge / monthDeaths.length)
      } else {
        // 模拟数据：基于真实趋势的平均寿命，考虑季节性因素
        const baseLifespan = 75
        const seasonalFactor = Math.sin((i / 12) * 2 * Math.PI) * 2 // 季节性波动
        const randomFactor = (Math.random() - 0.5) * 3 // 随机波动
        avgLifespan = Math.round(baseLifespan + seasonalFactor + randomFactor)
      }

      monthlyData.push(avgLifespan)
    }

    console.log('寿命趋势数据:', monthlyData)

    // 初始化ECharts实例
    const chart = echarts.init(trendChart.value, 'dark')

    // 配置图表选项
    const option = {
      backgroundColor: 'transparent',
      title: {
        text: '寿命趋势分析',
        subtext: hasRealData ? '基于实际数据的月度平均寿命变化' : '模拟数据：月度平均寿命变化趋势',
        left: 'center',
        textStyle: {
          color: '#ffffff',
          fontSize: 16
        },
        subtextStyle: {
          color: 'rgba(255, 255, 255, 0.8)',
          fontSize: 12
        }
      },
      tooltip: {
        trigger: 'axis',
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        borderColor: '#52c41a',
        textStyle: {
          color: '#ffffff'
        },
        formatter: function (params) {
          const item = params[0]
          return `${item.name}<br/>平均寿命: ${item.value}岁`
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: monthLabels,
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.5)'
          }
        },
        axisLabel: {
          color: 'rgba(255, 255, 255, 0.8)',
          fontSize: 10
        }
      },
      yAxis: {
        type: 'value',
        name: '年龄(岁)',
        min: 60,
        max: 90,
        nameTextStyle: {
          color: 'rgba(255, 255, 255, 0.8)'
        },
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.5)'
          }
        },
        axisLabel: {
          color: 'rgba(255, 255, 255, 0.8)',
          fontSize: 10
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.1)'
          }
        }
      },
      series: [
        {
          name: '平均寿命',
          type: 'line',
          data: monthlyData,
          smooth: true,
          lineStyle: {
            color: '#52c41a',
            width: 3
          },
          itemStyle: {
            color: '#52c41a',
            borderColor: '#ffffff',
            borderWidth: 2
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(82, 196, 26, 0.3)' },
              { offset: 1, color: 'rgba(82, 196, 26, 0.05)' }
            ])
          },
          label: {
            show: true,
            position: 'top',
            color: '#ffffff',
            fontSize: 10
          },
          markLine: {
            data: [
              {
                type: 'average',
                name: '平均值',
                lineStyle: {
                  color: '#faad14'
                },
                label: {
                  formatter: '平均: {c}岁',
                  color: '#ffffff'
                }
              }
            ]
          }
        }
      ]
    }

    // 设置图表选项
    chart.setOption(option)

    // 响应式调整
    window.addEventListener('resize', () => {
      chart.resize()
    })

    console.log('寿命趋势图绘制完成')
  } catch (error) {
    console.error('绘制寿命趋势图时出错:', error)
  }
}

const drawPredictionChart = () => {
  console.log('开始绘制寿命预测图')

  if (!predictionChart.value) {
    console.log('寿命预测图表容器不存在')
    return
  }

  try {
    // 计算预测数据
    const currentYear = dayjs().year()
    const years = []
    const predictedLifespan = []
    const confidenceUpper = []
    const confidenceLower = []

    for (let i = 0; i < 10; i++) {
      const year = currentYear + i
      years.push(year.toString())

      // 基于当前数据预测未来寿命趋势
      const baseLifespan = 75 + i * 0.5 // 假设每年增长0.5岁
      const variation = Math.random() * 2 - 1 // 随机波动

      const predicted = Math.round(baseLifespan + variation)
      const upper = predicted + 3
      const lower = predicted - 3

      predictedLifespan.push(predicted)
      confidenceUpper.push(upper)
      confidenceLower.push(lower)
    }

    console.log('寿命预测数据:', predictedLifespan)

    // 初始化ECharts实例
    const chart = echarts.init(predictionChart.value, 'dark')

    // 配置图表选项
    const option = {
      backgroundColor: 'transparent',
      title: {
        text: '寿命预测',
        subtext: '未来10年平均寿命预测',
        left: 'center',
        top: 0,
        textStyle: {
          color: '#ffffff',
          fontSize: 16,
          fontWeight: 'bold'
        },
        subtextStyle: {
          color: 'rgba(255, 255, 255, 0.8)',
          fontSize: 12
        }
      },

      tooltip: {
        trigger: 'axis',
        backgroundColor: 'rgba(0, 0, 0, 0.9)',
        borderColor: '#722ed1',
        borderWidth: 2,
        textStyle: {
          color: '#ffffff',
          fontSize: 12
        },
        axisPointer: {
          type: 'cross',
          lineStyle: {
            color: '#722ed1',
            type: 'dashed',
            width: 2
          },
          crossStyle: {
            color: '#722ed1',
            width: 1,
            opacity: 0.6
          },
          animation: true
        },
        formatter: function (params) {
          if (!params || params.length === 0) return ''

          let predictionValue = 0
          let confidenceRange = ''

          params.forEach((param) => {
            if (param.seriesName === '预测寿命') {
              predictionValue = param.value
              // 计算置信区间范围
              const upper = predictionValue + 3
              const lower = predictionValue - 3
              confidenceRange = `${lower}-${upper}岁`
            }
          })

          return `<div style="padding: 8px; background: rgba(0,0,0,0.9); border-radius: 6px;">
            <div style="font-weight: bold; margin-bottom: 8px; color: #722ed1; font-size: 14px;">
              📊 ${params[0].name}年寿命预测
            </div>
            <div style="margin-bottom: 6px; display: flex; justify-content: space-between;">
              <span style="color: rgba(255,255,255,0.8);">预测寿命:</span>
              <span style="color: #52c41a; font-weight: bold; font-size: 16px;">${predictionValue}岁</span>
            </div>
            <div style="margin-bottom: 4px; display: flex; justify-content: space-between;">
              <span style="color: rgba(255,255,255,0.8);">置信区间:</span>
              <span style="color: #faad14; font-weight: bold;">${confidenceRange}</span>
            </div>
            <div style="margin-top: 6px; padding-top: 6px; border-top: 1px solid rgba(255,255,255,0.2); font-size: 12px; color: rgba(255,255,255,0.6);">
              💡 悬停查看详细预测数据
            </div>
          </div>`
        }
      },
      legend: {
        data: ['置信区间', '预测寿命'],
        textStyle: {
          color: '#ffffff',
          fontSize: 12
        },
        right: 20,
        itemGap: 20
      },
      grid: {
        left: '8%',
        right: '8%',
        bottom: '0%',
        top: '25%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: years,
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.5)'
          }
        },
        axisLabel: {
          color: 'rgba(255, 255, 255, 0.8)',
          fontSize: 11,
          interval: 1, // 只显示每隔一个年份标签，避免重叠
          rotate: 0,
          margin: 12
        },
        axisTick: {
          alignWithLabel: true,
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.4)'
          }
        }
      },
      yAxis: {
        type: 'value',
        name: '年龄(岁)',
        nameLocation: 'middle',
        nameGap: 35,
        nameTextStyle: {
          color: 'rgba(255, 255, 255, 0.9)',
          fontSize: 12,
          fontWeight: 'bold'
        },
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.5)'
          }
        },
        axisLabel: {
          color: 'rgba(255, 255, 255, 0.8)',
          fontSize: 11
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.1)',
            type: 'dashed'
          }
        }
      },
      series: [
        {
          name: '置信区间',
          type: 'line',
          data: confidenceUpper,
          lineStyle: {
            opacity: 0
          },
          stack: 'confidence-band',
          symbol: 'none'
        },
        {
          name: '置信区间',
          type: 'line',
          data: confidenceLower.map((lower, index) => confidenceUpper[index] - lower),
          lineStyle: {
            opacity: 0
          },
          areaStyle: {
            color: 'rgba(114, 46, 209, 0.2)'
          },
          stack: 'confidence-band',
          symbol: 'none'
        },
        {
          name: '预测寿命',
          type: 'line',
          data: predictedLifespan,
          smooth: true,
          lineStyle: {
            color: '#722ed1',
            width: 4
          },
          itemStyle: {
            color: '#722ed1',
            borderColor: '#ffffff',
            borderWidth: 3
          },
          symbolSize: 8,
          emphasis: {
            itemStyle: {
              color: '#722ed1',
              borderColor: '#ffffff',
              borderWidth: 4,
              shadowBlur: 10,
              shadowColor: '#722ed1'
            },
            symbolSize: 12
          },
          label: {
            show: false // 隐藏数据标签，避免重叠，数值可通过悬停查看
          },
          markPoint: {
            data: [
              {
                type: 'max',
                name: '峰值',
                itemStyle: {
                  color: '#fa8c16',
                  borderColor: '#ffffff',
                  borderWidth: 2
                },
                label: {
                  show: true,
                  color: '#ffffff',
                  fontSize: 12,
                  fontWeight: 'bold',
                  offset: [0, -15],
                  formatter: function (params) {
                    return `峰值\n${params.value}岁`
                  }
                }
              }
            ],
            symbolSize: 60
          }
        }
      ],
      // 添加动画效果
      animation: true,
      animationDuration: 1500,
      animationEasing: 'cubicInOut'
    }

    // 设置图表选项
    chart.setOption(option)

    // 响应式调整
    window.addEventListener('resize', () => {
      chart.resize()
    })

    console.log('寿命预测图绘制完成')
  } catch (error) {
    console.error('绘制寿命预测图时出错:', error)
  }
}

// 工具方法
const getStatusBadge = (status) => {
  const statusMap = {
    normal: 'success',
    warning: 'warning',
    critical: 'error'
  }
  return statusMap[status] || 'default'
}

const getStatusText = (status) => {
  const textMap = {
    normal: '正常',
    warning: '预警',
    critical: '危险'
  }
  return textMap[status] || '未知'
}

const getProgressColor = (level) => {
  const colors = {
    high: '#ff4d4f',
    medium: '#faad14',
    low: '#52c41a'
  }
  return colors[level] || '#d9d9d9'
}

const getRemainingColor = (remaining) => {
  if (remaining < 5) return '#ff4d4f'
  if (remaining < 15) return '#faad14'
  return '#52c41a'
}

const getWarningColor = (level) => {
  const colors = {
    high: 'red',
    medium: 'orange',
    low: 'green'
  }
  return colors[level] || 'default'
}

const getWarningText = (level) => {
  const texts = {
    high: '高危',
    medium: '中度',
    low: '正常'
  }
  return texts[level] || '未知'
}

const getAlertColor = (level) => {
  const colors = {
    critical: 'red',
    warning: 'orange',
    info: 'blue'
  }
  return colors[level] || 'default'
}

const formatTime = (timeString) => {
  return dayjs(timeString).format('YYYY-MM-DD HH:mm')
}

const formatDateRange = (range) => {
  if (!range || range.length !== 2) return '未指定'
  return `${range[0].format('YYYY-MM-DD')} 至 ${range[1].format('YYYY-MM-DD')}`
}

// 生命周期
onMounted(() => {
  nextTick(() => {
    // 只在监控页面初始化时绘制生命周期图
    if (activeTab.value === 'monitor') {
      drawLifecycleChart()
    }
  })
})
</script>

<style lang="scss" scoped>
@use '@/styles/variables.scss' as *;

.lifespan-tracking {
  .tracking-tabs {
    margin-bottom: 24px;
    text-align: center;
  }

  .status-card {
    .status-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid $border-color;

      &:last-child {
        border-bottom: none;
      }

      .status-label {
        color: $text-secondary;
        font-size: 14px;
      }

      .status-value {
        font-weight: bold;
        color: $text-primary;

        &.warning {
          color: #faad14;
        }
      }
    }
  }

  .lifecycle-chart,
  .trend-chart,
  .prediction-chart {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 300px;
  }

  .trend-controls {
    margin-bottom: 16px;
  }

  .prediction-summary {
    margin-bottom: 16px;

    .prediction-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 0;

      .prediction-label {
        color: $text-secondary;
      }

      .prediction-value {
        font-weight: bold;
        color: $primary-color;
      }
    }
  }

  .alert-list {
    .alert-item {
      display: flex;
      align-items: center;
      padding: 16px;
      margin-bottom: 12px;
      background: rgba(255, 255, 255, 0.05);
      border: 1px solid $border-color;
      border-radius: 8px;
      transition: all 0.3s ease;

      &:hover {
        background: rgba(255, 255, 255, 0.08);
      }

      .alert-icon {
        font-size: 24px;
        margin-right: 16px;
      }

      .alert-content {
        flex: 1;

        .alert-title {
          font-weight: 500;
          color: $text-primary;
          margin-bottom: 4px;
        }

        .alert-desc {
          font-size: 12px;
          color: $text-secondary;
          margin-bottom: 4px;
        }

        .alert-time {
          font-size: 11px;
          color: $text-tertiary;
        }
      }

      .alert-actions {
        .ant-btn {
          margin-left: 8px;
        }
      }

      &.critical {
        border-left: 4px solid #f5222d;
        background: rgba(245, 34, 45, 0.1);

        .alert-icon {
          color: #f5222d;
        }
      }

      &.warning {
        border-left: 4px solid #faad14;
        background: rgba(250, 173, 20, 0.1);

        .alert-icon {
          color: #faad14;
        }
      }

      &.info {
        border-left: 4px solid #1890ff;
        background: rgba(24, 144, 255, 0.1);

        .alert-icon {
          color: #1890ff;
        }
      }
    }
  }

  .report-content {
    .report-summary {
      margin-bottom: 32px;

      h3 {
        color: $text-primary;
        margin-bottom: 16px;
      }
    }

    .report-details {
      h3 {
        color: $text-primary;
        margin-bottom: 16px;
      }
    }
  }

  .empty-report {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 300px;
  }

  .detail-content {
    color: $text-primary;
  }
}
</style>
